package com.gjs.freechat.server.component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.gjs.freechat.server.component.bean.ChatSession;
import com.gjs.freechat.server.component.bean.Conversation;


@Component
public class UserSessionPool {
	
	private static final Logger logger = Logger.getLogger(UserSessionPool.class);
	
	private Map<String, List<Conversation>> convosPool;
	private List<ChatSession> chatSessionsList;
	private AtomicInteger allConvosCount;
	
//	class RunTest implements Runnable {
//		
//		private Map<String, List<Conversation>> convosPool;
//		
//		
//		
//		public RunTest(Map<String, List<Conversation>> convosPool) {
//			this.convosPool = convosPool;
//		}
//		
//		@Override
//		public void run() {
//			while (true) {
//				if (convosPool.size() == 0) {
//					System.out.println(convosPool + "---------");
//				} else if (convosPool.size() > 0) {
//					System.out.println(convosPool + "+++++++++");
//				}
//			}
//		}
//	}
		
	
	public UserSessionPool() {
		convosPool = new ConcurrentHashMap<String, List<Conversation>>();
		chatSessionsList = Collections.synchronizedList(new LinkedList<ChatSession>());
		allConvosCount = new AtomicInteger(0);
		//new Thread(new RunTest(convosPool)).start();
	}
	
	public void addConversations(String userId, List<Conversation> convos) {
		List<Conversation> existedConvos = getExistedConvos(userId);
		if (existedConvos == null) {
			existedConvos = convos;
			convosPool.put(userId, existedConvos);
			logger.info("userId:" + userId + "用户会话注册,当前此用户会话数:" + convosPool.size());
		} else {
			existedConvos.addAll(convos);
		}
		allConvosCount.addAndGet(convos.size());
		logger.info("userId:" + userId + ",增加"+ convos.size() + "个会话,当前此用户会话数:" + convosPool.size() + "会话总数:" + allConvosCount.get());
	}
	
	public List<Conversation> getExistedConvos(String userId) {
		return convosPool.get(userId);
	}
	
	public List<String> getConvoPartnerIds(String userId) {
		List<String> partnerIds = new ArrayList<String>();
		List<Conversation> convos = convosPool.get(userId);
		if (convos == null)
			return partnerIds;
		for (Conversation convo : convos) {
			partnerIds.add(convo.getPartnerId());
		}
		return partnerIds;
	}
	
	
	public void addConvo(Conversation convo) {
		String userId = convo.getUserId();
		List<Conversation> existedConvos = getExistedConvos(userId);
		if (existedConvos == null) {
			existedConvos = Collections.synchronizedList(new ArrayList<Conversation>());
			convosPool.put(userId, existedConvos);
		}
		existedConvos.add(convo);
		allConvosCount.incrementAndGet();
		logger.info("userId:" + userId + "增加"+ 1 + "个会话,当前此用户会话数:" + convosPool.size() + "会话总数:" + allConvosCount);
	}
	
	public Conversation getConvo(String userId, String sessionId) {
		List<Conversation> convos = convosPool.get(userId);
		for (Conversation convo : convos) {
			if (convo.getId().equals(sessionId))
				return convo;
		}
		return null;
	}
	
	public boolean containConvo(String userId, String partnerId) {
		List<Conversation> convos = getExistedConvos(userId);
		for (Conversation convo : convos) {
			if (convo.getPartnerId().equals(partnerId)) {
				return true;
			}
		}
		return false;
	}
	
	public void registerConvos(String userId, List<Conversation> noThreadSafeConvos) {
		List<Conversation> convos = Collections.synchronizedList(new ArrayList<Conversation>(noThreadSafeConvos.size()));
		for (Conversation oldConvo : noThreadSafeConvos) {
			Conversation newConvo = new Conversation(oldConvo.getId(), oldConvo.getType(), oldConvo.getUserId(), oldConvo.getPartner(), 0);
			convos.add(newConvo);
		}
		addConversations(userId, convos);
	}
	
	public void addSessions(List<ChatSession> chatSessions) {
		chatSessionsList.addAll(chatSessions);
	}

	public boolean addSession(ChatSession session) {
		synchronized (chatSessionsList) {
			if (!chatSessionsList.contains(session)) {
				return chatSessionsList.add(session);
			}
			return false;
		}
		
	}
	
	public ChatSession getSession(String userId, String partnerId) {
		ChatSession chatSession = new ChatSession(null, 0, userId, partnerId);
		return chatSessionsList.get(chatSessionsList.indexOf(chatSession));
	}
	
	public void removeSession(ChatSession session) {
		chatSessionsList.remove(session);
	}
	
	public boolean containChatSession(ChatSession session) {
		return chatSessionsList.contains(session);
	}
	
	public void removeConvos(String userId) {
		convosPool.remove(userId);
	}
	
	public void removeConvo(String userId, String convoId) {
		List<Conversation> convos = convosPool.get(userId);
		if (convos == null)
			return;
		synchronized (convos) {
			int index = -1;
			for (int i = 0; i < convos.size(); i++) {
				if (convos.get(i).getId().equals(convoId)) {
					index = i;
				}
			}
			if (index != -1) 
				convos.remove(index);
		}
	}
}


